
/**
 * 科目详情对话框
 */
var ZxKemuInfoDlg = {
    data: {
        btyZxKemuId: "",
        name: ""
    }
};

layui.define(['layer', 'table', 'form','admin','ax','upload','func','laydate'], function (exports) {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var layer = layui.layer;
    var func = layui.func;
    var laydate = layui.laydate;
    /**
     * 管理
     */
    var ZxChengbenMingxi = {
        tableId: "zxChengbenMingxiTable"
    };

    form.verify({
        double: function (value) {
            var patt2=/^(\-|\+)?\d+(\.\d+)?$/;
            if (patt2.test(value) == false) {
                return '你输入的不是数字';
            }
        }
    });

    /**
     * 初始化表格的列
     */
    ZxChengbenMingxi.initColumn = function () {
        return [[
            // {type: 'checkbox'},
            {field: 'dh',width: 180,sort: true, title: '报销单号' },
            {field: 'btyyBxdaIdView',width: 100, sort: true, title: '报销人'},
            {
                field: 'createTime', width: 110, sort: true, title: '提交日期', templet: function (data) {
                    return layui.util.toDateString(data.createTime, "yyyy-MM-dd");
                }
            },
            {field: 'btyZxChengbenMingxiId', hide: true, title: ''},
            {field: 'btyBrandIdView', width: 250, sort: true, title: '门店'},
            {field: 'btyZxMdzxId', sort: true, title: '门店id',hide: true},
            // {field: 'btyZxKemuIdView', sort: true, title: '科目'},
            {field: 'qtkm', sort: true, title: '货品'},
            {field: 'shuliang', sort: true,width: 90, title: '数量'},
            {field: 'unitPrice', sort: true,width: 90, title: '单价'},
            {field: 'bxjine', sort: true,width: 120, title: '报销金额',totalRow: true},
            {field: 'jine', sort: true,width: 120, title: '确认金额',totalRow: true},
            {field: 'beizhu', sort: true, title: '备注'},
            {field: 'status', templet: '#statusTpl2',sort: true, title: '状态',width: 120}
        ]];
    };

    laydate.render({
        elem: '#riqi1',
        format: 'yyyy-MM-dd',
        // value:Feng.currentDate(),
        max: Feng.currentDate()
    });

    //监听单元格编辑-编辑备注和备忘时
    table.on('edit(zxChengbenMingxiTable)', function (obj) {
        //得到修改后的值
        var value = obj.value,
            //得到所在行所有键值
            data = obj.data,
            //得到字段
            field = obj.field;
        if (field == "shuliang" && isNaN(value)) {
            Feng.error("修改失败，数量必须填写数字");
            return false;
        }
        //金额字段校验
        if (field == "unitPrice" && isNaN(value)) {
            Feng.error("修改失败，单价必须填写数字");
            return false;
        }

        var shuliang = data.shuliang;
        var unitPrice = data.unitPrice;
        var jine = shuliang * unitPrice;
        data.jine=jine;

        $.ajax({
            type: "PUT",
            url: "/dgdzxChengbenMingxi/editItemGhs",
            datatype: "json",
            data: data,
            success: function (data) {
                if (data.code != 200) {
                    Feng.error(data.message);
                    table.reload(ZxChengbenMingxi.tableId);
                }else {
                    table.reload(ZxChengbenMingxi.tableId);
                }
            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) {
            }
        });
    });

    /**
     * 点击查询按钮
     */
    ZxChengbenMingxi.search = function () {
        var queryData = {};
        queryData['btyZxMdzxId'] = $("#btyZxMdzxId").val();
        queryData['createDakuanDan'] = $("#createDakuanDan").val();
        queryData['btyyBxdaId'] = $("#btyyBxdaId").val();
        queryData['btyZxChengbenId'] = $("#btyZxChengbenId").val();
        queryData['huopinId'] = $("#huopinId").val();
        queryData['riqi'] = $("#riqi1").val();
        queryData['createUser'] = $("#createUser").val();
        queryData['status'] = $("#status").val();
        table.reload(ZxChengbenMingxi.tableId, {where: queryData});
    };

    /**
     * 弹出添加对话框
     */
    ZxChengbenMingxi.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/dgdzxChengbenMingxi/add';
    };

    /**
     * 导出excel按钮
     */
    // ZxChengbenMingxi.exportExcel = function () {
    //     var checkRows = table.checkStatus(ZxChengbenMingxi.tableId);
    //     if (checkRows.data.length === 0) {
    //         Feng.error("请选择要导出的数据");
    //     } else {
    //         table.exportFile(tableResult.config.id, checkRows.data, 'xls');
    //     }
    // };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    ZxChengbenMingxi.openEditDlg = function (data) {
        var url = Feng.ctxPath + '/dgdzxChengbenMingxi/editGhs?btyZxChengbenMingxiId=' + data.btyZxChengbenMingxiId+"&btyZxChengbenId="+data.btyZxChengbenId
            +"&btyZxKemuId="+data.btyZxKemuId+"&btyZxKemuIdView="+encodeURIComponent(data.btyZxKemuIdView);
        // window.location.href = url;

        parent.layer.open({
            type: 2,
            title: '修改报销明细',
            area: ['800px', '800px'],
            content: url,
            end: function () {
                ZxChengbenMingxi.search();
            },
            cancel:function (index){
                ZxChengbenMingxi.search();
            }
        });

    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    ZxChengbenMingxi.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/dgdzxChengbenMingxi/deleteGhs", function (data) {
                if (data.code == 200) {
                    Feng.success("删除成功!");
                    table.reload(ZxChengbenMingxi.tableId);
                    init_btyZxChengbenId();
                }else {
                    Feng.error("删除失败!");
                }
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("btyZxChengbenMingxiId", data.btyZxChengbenMingxiId);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    var init_btyyBxdaId = $("#btyyBxdaId").val();
    if(init_btyyBxdaId==""){
        init_btyyBxdaId = $("#btyyBxdaKey").val();
    }
    // 渲染表格
    var tableResult = table.render({
        elem: '#' + ZxChengbenMingxi.tableId,
        //参数来自zxChengben.js
        url: Feng.ctxPath + '/dgdzxChengbenMingxi/list',
        page: false,
        height: "full-128",
        cellMinWidth: 100,
        totalRow: true,
        limit: 90,
        where:{
            btyyBxdaId:init_btyyBxdaId,
            riqi:Feng.currentDate()
        },
        cols: ZxChengbenMingxi.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        ZxChengbenMingxi.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        ZxChengbenMingxi.openAddDlg();
    });

    // // 导出excel
    // $('#btnExp').click(function () {
    //     ZxChengbenMingxi.exportExcel();
    // });

    // 工具条点击事件
    table.on('tool(' + ZxChengbenMingxi.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            ZxChengbenMingxi.openEditDlg(data);
        } else if (layEvent === 'delete') {
            ZxChengbenMingxi.onDeleteItem(data);
        }
    });

    var loading;
    layui.upload.render({
        elem: '#btnImportMdbx'
        , url: '/dgdzxChengbenMingxi/btnImportMdbx'
        , accept: "file"
        , async: false
        //, data: {"btyZxChengbenId":Feng.getUrlParam("btyZxChengbenId")}
        , exts: 'xls|xlsx'
        , before: function () {
            //this.data = {'dataTime': $('#dataTime').val()};//关键代码
            loading = layer.load(2, {shade: [0.15, '#ccc']});
        }
        , done: function (data) {
            if (data.code == 200) {
                layer.close(loading);
                Feng.success("导入成功");
            } else {
                layer.close(loading);
                Feng.error(data.message);
            }
            ZxChengbenMingxi.search();
        }
    });

    // 点击科目时
    $('#btyZxKemuIdView').click(function () {
        var formName = encodeURIComponent("parent.ZxKemuInfoDlg.data.name");
        var formId = encodeURIComponent("parent.ZxKemuInfoDlg.data.btyZxKemuId");
        var treeUrl = encodeURIComponent("/zxKemu/tree");
        layer.open({
            type: 2,
            title: '科目选择（请双击选择）',
            area: ['50%', '80%'],
            content: Feng.ctxPath + '/system/commonTree?formName=' + formName + "&formId=" + formId + "&treeUrl=" + treeUrl,
            end: function () {
                $("#btyZxKemuId").val(ZxKemuInfoDlg.data.btyZxKemuId);
                $("#btyZxKemuIdView").val(ZxKemuInfoDlg.data.name);
            }
        });
    });


    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var ajax = new $ax(Feng.ctxPath + "/dgdzxChengbenMingxi/addNewItemGhs", function (data) {
            if (data.code == 200) {
                Feng.success("保存成功");

                $("#unitPrice").val("");
                $("#jine").val("");
                $("#beizhu").val("");
                form.render('select');

                //刷新列表
                var queryData = {};
                //queryData['btyZxChengbenId'] = Feng.getUrlParam("btyZxChengbenId");
                table.reload(ZxChengbenMingxi.tableId, {where: queryData});
                table.reload(ZxChengbenMingxi.tableId);
            }else {
                Feng.error(data.message);
            }
        }, function (data) {
            Feng.error("添加失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.set("btyZxChengbenId","");
        ajax.start();
        return false;
    });


    function closePage(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    }

    //返回按钮
    $("#backupPage").click(function () {
        closePage();
        // window.location.href = Feng.ctxPath + '/dgdzxChengben'
    });


    //获取成本详情信息，填充门店选择框
    var ajax = new $ax(Feng.ctxPath + "/dgdzxChengben/detail");
    var result = ajax.start();

    function init_btyZxChengbenId() {
        $("#btyZxChengbenId").empty();
        $("#btyZxChengbenId").append("<option value=''>请选择</option>");
        var languageAjax = new $ax(Feng.ctxPath + "/dgdzxChengben/listBh");
        var btyyBxdaId = $("#btyyBxdaId").val();
        if(btyyBxdaId==""){
            btyyBxdaId = $("#btyyBxdaKey").val();
        }
        languageAjax.set("btyyBxdaId",btyyBxdaId);
        var languageResult = languageAjax.start();
        $.each(languageResult.data, function (index, val) {
            if(val.company!=undefined){
                //添加的门店
                $("#btyZxChengbenId").append("<option value='" + val.btyZxChengbenId + "'>" + val.company  + "</option>");
            }
        });
        form.render('select');
    }
    init_btyZxChengbenId();
    /**
     * 初始门店
     */
    function init_btyZxMdzxId(){
        $("#btyZxMdzxId").empty();
        $("#btyZxMdzxId").append("<option value=''>请选择</option>");
        var languageAjax = new $ax(Feng.ctxPath + "/dgdmdzx/mdzxList");
        var languageResult = languageAjax.start();
        $.each(languageResult.data, function (index, val) {
            if(val.btyBrandIdView!=undefined){
                var pinyin = ConvertPinyin(val.btyBrandIdView);
                //添加的门店
                $("#btyZxMdzxId").append("<option value='" + val.btyZxMdzxId + "'>" + val.btyBrandIdView  + "</option>");

                //查询用的门店
                $("#btyZxMdzxId1").append("<option value='" + val.btyZxMdzxId + "'>" + val.btyBrandIdView + "</option>");
            }
        });
        form.render('select');
    }
    init_btyZxMdzxId();

    //金额与公式联动
    $("#jine").on("input",function(e){
       var jine=$("#jine").val();
        $("#gongshi").val("");
        if(jine!=""){
            $("#gongshi").val(jine);
        }
    });

    /**
     * 初始化厂家-报销人
     */

    
    function init_btyyBxdaId() {
        $("#btyyBxdaId").empty();
        $("#btyyBxdaId").append("<option value=''>请选择</option>");

        var languageAjax = new $ax(Feng.ctxPath + "/btyBxda/getAllVendorList");
        var languageResult = languageAjax.start();
        $.each(languageResult.data, function (index, val) {
            var pinyin = ConvertPinyin(val.xm);

            $("#btyyBxdaId").append("<option value='" + val.yhk + "'>" + val.xm +"-"+ val.yhk+"-"+ pinyin + "</option>");
        });
        form.render('select');
    }

    var huopinArr = null;
    /**
     * 初始关键字-其它科目-三级科目
     */
    function init_huopinId(){
        $("#huopinId").empty();
        $("#huopinId").append("<option value=''>请选择</option>");
        var languageAjax = new $ax(Feng.ctxPath + "/dgdzxHuopin/list");
        languageAjax.set("ghs",$("#btyyBxdaKey").val());
        var languageResult = languageAjax.start();
        huopinArr=languageResult.data;
        $.each(languageResult.data, function (index, val) {
            if(val.btyZxHuopinId!=undefined){
                $("#huopinId").append("<option value='" + val.btyZxHuopinId + "'>" + val.name+ "</option>");
            }
        });
        form.render('select');
    }
    init_huopinId();

    //选择货品时，将货品名称赋值给摘要
    form.on('select(huopinId)',function (data) {
        var huopinId= $("#huopinId").val();
        if(huopinId!="") {
            $.each(huopinArr, function (index, val) {
                if(val.btyZxHuopinId==huopinId){
                    $("#qtkm").val(val.name);
                    $("#unitPrice").val(val.danjia);
                    calJe();
                }
            });
        }
    });

    //选择货品时，将货品名称赋值给摘要
    form.on('select(btyZxChengbenId)',function (data) {
        ZxChengbenMingxi.search();
    });

    function init_createUser(){
        $("#createUser").empty();
        $("#createUser").append("<option value=''>全部</option>");
        var languageAjax = new $ax(Feng.ctxPath + "/dgdzxChengbenMingxi/queryCreateUser");
        var languageResult = languageAjax.start();
        console.info(languageResult);
        var userid = languageResult.data.userid;
        $.each(languageResult.data.list, function (index, val) {
            var selected = "";
            if(val.value==userid){
                selected = "selected";
            }
            $("#createUser").append("<option value='" + val.value + "' "+selected+">" + val.label + "</option>");
        });
        form.render('select');
    }
    init_createUser();

    function calJe(){
        var shuliang = $("#shuliang").val();
        var unitPrice = $("#unitPrice").val();
        if(unitPrice==""){
            $("#jine").val("");
            return;
        }
        var jine = shuliang * unitPrice;
        $("#jine").val(jine.toFixed(2));
    }

    $("#shuliang").blur(function (data) {
        calJe();
    });
    $("#unitPrice").blur(function (data) {
        calJe();
    });


    // 添加按钮点击事件
    $('#bxdaAdd').click(function () {
        layer.open({
            type: 2,
            title: '添加报销档案', //不显示标题(false)
            shadeClose: true,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['70%', '60%'],
            end: function (index) {
                //刷新
                init_btyyBxdaId();
            },
            content: Feng.ctxPath + '/btyBxda/btyBxda_add2'
        });
    });
    // 添加按钮点击事件
    $('#gjz_sx').click(function () {
        init_huopinId();
    });
    $('#bxr_sx').click(function () {
        init_btyyBxdaId()
    });
    $('#md_sx').click(function () {
        init_btyZxMdzxId()
    });


    // 添加按钮点击事件
    $('#kemuKeyAdd').click(function () {
        layer.open({
            type: 2,
            title: '添加科目关键字', //不显示标题(false)
            shadeClose: true,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['60%', '60%'],
            end: function (index) {
                //刷新
                init_huopinId();
            },
            content: Feng.ctxPath + '/zxKemuKey'
        });


    });

    //添加完报销人，刷新报销人列表
    exports('shuxinBaoXiaoRen', function () {
        if(1==1){
            ZxChengbenMingxi.reloadSelect();
        }
    });

    //重新加载报销人select
    ZxChengbenMingxi.reloadSelect = function (newyinhangka) {
        $("#btyyBxdaId").html("");
        $("#btyyBxdaId").append("<option value=''>" + "请选择"+"</option>");
        var languageAjax = new $ax(Feng.ctxPath + "/btyBxda/getAllVendorList");
        var languageResult = languageAjax.start();
        console.info(languageResult);

        $.each(languageResult.data, function (index, val) {
                var pinyin = ConvertPinyin(val.xm);
                $("#btyyBxdaId").append("<option value='" + val.yhk + "'>" + val.xm +"-"+ val.yhk+"-"+ pinyin + "</option>");
        });
        $("#btyyBxdaId").val(newyinhangka);
        form.render('select');
    };

    // 刷新页面
    $('#refresh').click(function () {
        window.location.href = Feng.ctxPath + '/dgdzxChengbenMingxi/dgdzxChengbenMingxiNew';
    });


    // 刷新页面
    $('#createDakuandan1').click(function () {
        var operation = function () {
            $.ajax({
                url: Feng.ctxPath + "/dgdzxChengbenMingxi/tijiaobaoxiaoGhs",
                cache: false,
                dataType:"json",
                data:  {'btyyBxdaId':$("#btyyBxdaId").val()},
                timeout: 600*1000,//10min
                beforeSend: function () {

                },
                success: function (data) {
                    if (data.code == 200) {
                        Feng.success("提交成功!");
                        //刷新列表
                        var queryData = {};
                        queryData['btyZxMdzxId'] = Feng.getUrlParam("btyZxMdzxId");
                        table.reload(ZxChengbenMingxi.tableId, {where: queryData});
                        init_btyZxChengbenId();
                    }else {
                        Feng.error(data.message);
                    }
                },
                error: function (data) {
                    layer.alert('失败！');

                }
            });
        };
        Feng.confirm("是否提交报销?", operation);
    });
    $('#createDakuandan2').click(function () {
        var operation = function () {
            $.ajax({
                url: Feng.ctxPath + "/dgdzxChengbenMingxi/tijiaobaoxiaoGhsTh",
                cache: false,
                dataType:"json",
                data:  {'btyyBxdaId':$("#btyyBxdaId").val()},
                timeout: 600*1000,//10min
                beforeSend: function () {

                },
                success: function (data) {
                    if (data.code == 200) {
                        Feng.success("提交成功!");
                        //刷新列表
                        var queryData = {};
                        queryData['btyZxMdzxId'] = Feng.getUrlParam("btyZxMdzxId");
                        table.reload(ZxChengbenMingxi.tableId, {where: queryData});
                        init_btyZxChengbenId();
                    }else {
                        Feng.error(data.message);
                    }
                },
                error: function (data) {
                    layer.alert('失败！');

                }
            });
        };
        Feng.confirm("是否提交报销?", operation);
    });


    $('#btnQingkong').click(function () {
        $("#btyZxChengbenId").val("");
        $("#btyZxMdzxId").val("");
        $("#btyyBxdaId").val("");
        $("#huopinId").val("");
        $("#status").val("");
        form.render('select');
        $("#shuliang").val("1");
        $("#unitPrice").val("");
        $("#jine").val("");
        $("#beizhu").val("");
        $("#qtkm").val("");
        $("#riqi1").val("");
        $("#companyView").val("0.00");
    });
// 刷新页面

    function calChouddian(){
        if(isCheck){
            var zongjia = $("#jine").val();
            if(zongjia==""){
                zongjia="0";
            }
            var zongjia_d = parseFloat(zongjia);
            var xishu = parseFloat("0.05");
            var choudian_je = zongjia_d*xishu;
            $("#companyView").attr("value",choudian_je.toFixed(2));
        }else {
            $("#companyView").attr("value","0.00");
        }
    }

    var isCheck = false;
    form.on('checkbox(choudian)', function (data) {
        isCheck = data.elem.checked;
        calChouddian();
    });


});
